/* *****************************************************************************
 *
 *	danizone.ch
 *
 *	Developer:		mda010
 *	Creation date:	May 6, 2012 10:09:17 PM
 *	
 *	Project name:	HomegrownCuisine
 *	File name:		AdminController.java
 *
 *	Copyrights (C) 2012 @danizone.ch
 *
 *   This program is free software; you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation; either version 2 of the License, or
 *	(at your option) any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *	GNU General Public License for more details.
 *
 *	Change history:	[developer]; [date];[reason for change]
 *
 *					mda010; May 6, 2012; created
 *
 ***************************************************************************** */
package ch.zhaw.hgc.controllers;

import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.UUID;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import ch.zhaw.hgc.entities.UserAccount;
import ch.zhaw.hgc.services.IUserAccountService;


@Controller
@RequestMapping("/addUserAccount")
public class UserAccountController {
	
	private static final Logger logger = Logger
			.getLogger(UserAccountController.class);

	@Autowired
	private IUserAccountService userAccountService;

	
	/**
	 * @param userAccount
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView get(UserAccount userAccount) {
		
		ModelAndView model = new ModelAndView("addUserAccount");
		
		model.addObject("userAccounts", userAccountService.findAll());
		
		model.addObject("userAccount", new UserAccount());
		model.addObject("message", "");

		logger.info("Passed get() method in controller...");

		return model;
	}

	
	/**
	 * @param userAccount
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView submitUserAccount(@ModelAttribute("userAccount") UserAccount userAccount) {
		ModelAndView model = new ModelAndView("addUserAccount");
		
		userAccount.setValidationValue(UUID.randomUUID().toString());
		userAccount = userAccountService.save(userAccount);		
		this.sendMail(userAccount.getAccountName(), userAccount.getValidationValue());
		
		
		model.addObject("userAccount", new UserAccount());
		model.addObject("message", "Successfull saved... <br>You will receive an email shortly to activate your account.");
		model.addObject("userAccounts", userAccountService.findAll());
		return model;
	}
	
	public void sendMail(String userName, String validationValue){
	
		Properties props = new Properties();        
		Session session = Session.getDefaultInstance(props, null);        
		String msgBody = "Your account has been successfully createt \n" +
				"Please validate your accout with the following Link: " +
				"http://homegrown-cuisine.appspot.com/validation.jsp?val="+validationValue + //TODO get to current url
				" \n Grettings HomeGrownCuisine-Team";         
		try {            
			Message msg = new MimeMessage(session);            
			msg.setFrom(new InternetAddress("macenemeth@gmail.com", "Home Grown Cuisine"));     
			msg.addRecipient(Message.RecipientType.TO,                         
					new InternetAddress(userName, "Mr. User"));           
			msg.setSubject("Your " + userName + " account has been activated");         
			msg.setText(msgBody);          
			Transport.send(msg);            
			} catch (AddressException e) {  
				e.printStackTrace();
			        } catch (MessagingException e) {            
			        	e.printStackTrace();
			        } catch (UnsupportedEncodingException e) {
			        	e.printStackTrace();
					}
	}

	

}